package com.sojson.config.shardingJdbc;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.sojson.config.datasource.enums.EDataSourceType;

/**
 * ShardingJdbc配置类
 * 
 * @author liu
 * @date 2022-01-11
 */
@Configuration
public class ShardingConfig {

    /**
     * Bean名称去{org.apache.shardingsphere.shardingjdbc.spring.boot.SpringBootConfiguration}找
     * shardingjdbc有四种数据源，需要根据业务注入不同的数据源
     * 1. 未使用分片, 脱敏的名称(默认): shardingDataSource;
     * 2. 主从数据源: masterSlaveDataSource;
     * 3. 脱敏数据源：encryptDataSource;
     * 4. 影子数据源：shadowDataSource
     */
    @Resource
    ShardingSphereDataSource shardingSphereDataSource;

    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider() {
        return new AbstractDataSourceProvider() {
            @Override
            public Map<String, DataSource> loadDataSources() {
                Map<String, DataSource> map = new HashMap<>();
                map.put(EDataSourceType.sharding.toString(), shardingSphereDataSource);// 这里将shardingjdbc管理的数据源交给dynamic-datasource动态数据源去管理
                return map;
            }
        };
    }

}